from __future__ import absolute_import
import os
import datetime

from django.utils import timezone
from django.shortcuts import render, get_object_or_404, render_to_response
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.generic.edit import (FormView,
                                       UpdateView,
                                       CreateView,
                                       DeleteView,
                                       )
from django.template import Context, RequestContext
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session  # only for learn 
from .models import Poll, Choice
from .PollForm import PollForm
from .form_add import PollAddForm

from contacts.common_me import (print_request_user,
                                print_request_cookie,
                                print_request_session,
                                )


class ListView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        # _session =  Session.objects.get(pk = self.request.COOKIES.get('sessionid'))
        # print _session.get_decoded()['_auth_user_id']
        # print self.request.session
        # print dir(self.request)
        return Poll.objects.filter(pub_date__lte = timezone.now()).order_by('-pub_date')


class DetailView(generic.DetailView):
    model = Poll
    template_name = "polls/detail.html"
    context_object_name = 'poll'

    def get_queryset(self):
        poll_resu = Poll.objects.filter(pub_date__lte=timezone.now())
        return poll_resu

    def get(self, *args, **kwargs):
        return super(DetailView, self).get(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        context['manual_add'] = "Hello Django"
        print self.request.COOKIES
        return context


class ResultsView(generic.DetailView):
    model = Poll
    template_name = "polls/results.html"


class PollCreateView(CreateView):
    model = Poll
    fields = ['question', 'pub_date', 'created_by']
    template_name = 'polls/pollcreate.html'
    success_url = '/polls/'
    # form_class = PollForm

    def form_valid(self, form):
        #form.instance.created_by = self.request.user
        print self.request.user
        form.instance.created_by = User.objects.get(pk=1)
        form.instance.new_add = 'abcdefg'
        print dir(form.instance)
        return super(PollCreateView, self).form_valid(form)

    def post(self, request, *args, **kwargs):
        return super(PollCreateView, self).post(request, *args, **kwargs)


class PollEditView(UpdateView):
    model = Poll
    template_name = 'polls/polledit.html'
    success_url = '/polls/'
    ##form_class = PollAddForm


class PollDeleteView(DeleteView):
    model = Poll
    success_url = '/polls/'
    template_name = "polls/poll_confirm_delete.html"


class AboutView(generic.View):
    template_name = "polls/about.html"

    def get(self, request, *args, **kwargs):
        print "debug: %s" % (request.user)
        # return HttpResponse("<html><head><title>about</title></head><body>About</body</html>")
        return render_to_response('polls/about.html')


def my_form_post(request):
    if request.method == 'GET':
        form = PollForm(
            initial={'question': 'input your question',
                     'pub_date': '2014-01-01',
                     }
            )
        return render_to_response('polls/pollcreate.html',
                                  {'form': form},
                                  RequestContext(request),
                                  ##Context(request),
                                  )
    elif request.method == 'POST':
        form_post = PollForm(request.POST)
        print request.POST.get('question', None)
        print request.POST.get('pub_date', None)
        if form_post.is_valid():
            print "is_valid return True"
            s1 = Poll()
            s1.question = request.POST.get('question')
            s1.pub_date = request.POST.get('pub_date')
            s1.save()
            return HttpResponseRedirect('/polls/')
        print "is_valid return False"
        return render_to_response('polls/pollcreate.html',
                                  {'form': form_post},
                                  RequestContext(request),
                                  )

def display_meta(request):
    values = request.META.items()
    values.sort()
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    return HttpResponse('<table>%s</table>' % '\n'.join(html))


def display_meta_template(request):
    values = request.META.items()
    values.sort()
    return render_to_response('polls/meta_template.html',
                              {'metas': values},
                              RequestContext(request),
                              )

def search_form(request):
    return render_to_response('polls/search_form.html',
                              RequestContext(request),
                              )

def search(request):
    errors = []
    if request.POST.get('q', None):
        q = request.POST.get('q')
        polls = Poll.objects.filter(question__icontains=q)
        print polls
        ##print request.POST.items()
        return render_to_response('polls/search_form.html',
                                  {'polls': polls},
                                  RequestContext(request),
                                  )
    else:
        errors.append('please submit a search term.')
        return render_to_response('polls/search_form.html',
                                  {'errors': errors},
                                  RequestContext(request),
                                  )
        ##return HttpResponseRedirect('/polls/')


def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request,
                      'polls/detail.html',
                      {'poll': p,
                       'error_message': "You didn't select a choice.",})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        ## return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
        return HttpResponseRedirect(reverse('polls:index',))

def css(request):
    print_request_cookie(request)
    default = "polls/csslearn.html"
    return render_to_response(default, {'body': ""}, RequestContext(request))

def css_name(request, name):
    template_name = "polls/css" + name + ".html"
    return render_to_response(template_name, {'body': ""}, RequestContext(request))

def css_post(request):
    if request.method == "POST":
        print request.POST
        for key in request.POST:
            print request.POST[key]
    return HttpResponseRedirect(reverse('polls:css',))


def test_js(request, template_name=None):
    if not template_name:
        template_name = "test_js"
        return render_to_response("polls/" + template_name + ".html", {'body': ""})
    else:
        template_name = "test_" + template_name
        if os.path.exists("polls/" + template_name + ".html"):
            return render_to_response("polls/" + template_name + ".html", {'body': ""})
        else:
            response = HttpResponse()
            response["Content-Length"] = 256
            response["Content-Type"] = "text/html"
            response["Server"] = "Apache-2.22"
            response.write("<html><head><title>hi js</title></head><body>Hi JS</body></html>")
            return response
